package com.qf.filter;

import com.qf.pojo.User;
import com.qf.utils.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class LoginFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String uri = req.getRequestURI();

        if (uri.endsWith("login.html") || uri.endsWith("login")){

            return true;
        }


        User user = (User) req.getSession().getAttribute("user");
        if (user != null){

            //通过某种方式，将校验已经登录完成的用户信息向下传递（不可以使用session） -- ThreadLocal
            SecurityContextHolder.setContext(user);

            return true;
        }else{
            resp.sendRedirect("/login.html");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //保证ThreadLocal中的数据，使用完成后，及时释放，防止内存泄露 -->OOM(内存溢出)
        SecurityContextHolder.removeContext();
    }
}
